package com.cmlite;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cmlite.adapter.EventAdapter;
import com.cmlite.adapter.EventAdapter.OnClickListListener;
import com.cmlite.base.BaseActivity;
import com.cmlite.base.BaseInit;
import com.cmlite.component.ClearableEditText;
import com.cmlite.component.ClearableEditText.Listener;
import com.cmlite.connect.AsyncTask_Api;
import com.cmlite.connect.AsyncTask_ApiListener;
import com.cmlite.connect.CallApi;
import com.cmlite.connect.HTTPReq;
import com.cmlite.connect.ScreenStopper;
import com.cmlite.model.EventModel;
import com.cmlite.model.EventModelList;
import com.cmlite.util.ConnectionException;
import com.cmlite.util.EmptyDataException;
import com.cmlite.util.SharedPreferencesDB;
import com.cmlite.util.SideBar;
import com.cmlite.util.TokenUnableException;
import com.cmlite.util.Util;

public class A003ListEvent extends BaseActivity implements BaseInit,
		OnClickListener, TextWatcher, AsyncTask_ApiListener, Listener {
	private static final int A004_LOGOUT = 1;
	public static final int TYPE_GET = 0;
	private static final String TAG = A003ListEvent.class.getName();
	private ClearableEditText et_search;
	private ListView mListView;
	private TextView btn_title, btn_logout;
	private RelativeLayout a003_layout_listview;
	private SideBar mSideBar;
	private EventAdapter mAdapter;

	private EventModelList mEventListSource;
	private HashMap<String, List<EventModel>> dictDisplay;
	private String token;
	private Handler mHandler = new Handler();

	@Override
	public void onIOnCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		initView();
	}

	@Override
	public void onIRestart() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIStart() {

	}

	@Override
	public void onIResume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIDestroy() {
		onLogout(token);
		Log.d(TAG, "Destroy !!!!!");

	}

	private void onLogout(final String token) {
		if (Util.getNetworkStatus(getApplicationContext())) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						HTTPReq htreq = new HTTPReq(CallApi.SERVER);
						String format = String.format("/logout/%s", token);
						HashMap<String, String> hashMap = new HashMap<String, String>();
						htreq.post(getApplicationContext(), format, hashMap);
					} catch (EmptyDataException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ConnectionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (TokenUnableException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}).run();

		} else {
			Util.showDialog(getApplicationContext(), R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	@Override
	public void onIActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == A004_LOGOUT) {
			finish();
		}
	}

	@Override
	public void onIBackPressed() {
		// TODO Auto-generated method stub

	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.a003listevent);

		this.a003_layout_listview = (RelativeLayout) findViewById(R.id.a003_layout_listview);
		this.et_search = (ClearableEditText) findViewById(R.id.a003_et_search);
		this.et_search.setListener(this);
		this.mListView = (ListView) findViewById(R.id.a003_listview);
		final View v_footer = (View) findViewById(R.id.a003_footer);
		this.btn_logout = (TextView) v_footer.findViewById(R.id.footer_tv_back);
		this.btn_logout.setVisibility(View.VISIBLE);
		final View v_header = (View) findViewById(R.id.a003_header);
		this.btn_title = (TextView) v_header.findViewById(R.id.header_tv_title);
		this.mSideBar = (SideBar) findViewById(R.id.a003_sidebar);

		this.btn_logout.setOnClickListener(this);
		this.et_search.addTextChangedListener(this);

		this.btn_title.setText(mRes.getString(R.string.events));

		initData();
	}

	@Override
	public void initData() {
		dictDisplay = new HashMap<String, List<EventModel>>();
		getEventList();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.footer_tv_back:
			SharedPreferencesDB db = new SharedPreferencesDB(this);
			token = db.getPrefToken();
			finish();
			break;
		default:
			break;
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		if (s.toString().trim().length() > 0) {
			final String search = ".*" + s.toString().trim() + ".*";
			updateListView(mEventListSource.getmListEvent(), search);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	@Override
	public Object callApi(int serachType, Object apidata) {
		// TODO Auto-generated method stub
		if (serachType == TYPE_GET) {
			try {
				SharedPreferencesDB db = new SharedPreferencesDB(this);
				return CallApi.getEvents(mContext, db.getPrefToken(), 25, 0,
						null, null, null);
			} catch (EmptyDataException e) {
				e.printStackTrace();
			} catch (ConnectionException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (TokenUnableException e) {
				callBackLogin(e.getMessage());
			}
		}
		return null;
	}

	private void callBackLogin(String message) {
		Intent i = new Intent(this, A1002Login.class);
		i.putExtra("message", message);
		setResult(1, i);
		finish();
	}

	@Override
	public void finishApi(int serachType, Object apiresult) {
		// TODO Auto-generated method stub
		try {
			if (serachType == TYPE_GET) {
				if (apiresult != null) {
					initEventList();
					mEventListSource = (EventModelList) apiresult;
					updateListView(mEventListSource.getmListEvent(), null);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void tokenExpride() {
		// TODO Auto-generated method stub

	}

	private void getEventList() {
		try {
			if (Util.getNetworkStatus(mContext)) {
				AsyncTask_Api apiTask = new AsyncTask_Api(this, this, TYPE_GET,
						0, ScreenStopper.STYLE_PROGRESS_PROCESS);
				apiTask.execute();
			} else {
				Util.showDialog(this, R.string.warning,
						R.string.network_not_available, R.drawable.exclamation);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void initEventList() {
		if (mEventListSource != null) {
			mEventListSource.getmListEvent().clear();
			mEventListSource = null;
		}
		mEventListSource = new EventModelList();
	}

	private int index = 1;

	public void updateListView(List<EventModel> data, String search) {
		dictDisplay.clear();
		Collections.sort(data, new Comparator<EventModel>() {
			@Override
			public int compare(EventModel lhs, EventModel rhs) {
				return lhs.getValueByIndex(index).compareTo(
						rhs.getValueByIndex(index));
			}
		});
		List<EventModel> events = new ArrayList<EventModel>();
		boolean isColor = true;
		if (search != null) {
			for (EventModel event : data) {
				if (event.getValueByIndex(index).toLowerCase()
						.matches(search.toLowerCase())) {
					String value = event.getValueByIndex(index).trim();
					String key = value.substring(0, 1).toUpperCase();
					List<EventModel> values = dictDisplay.get(key);
					if (values == null) {
						values = new ArrayList<EventModel>();
						final EventModel p = new EventModel();
						p.setEventName(key);
						// System.out.println("KEY: " + key);
						p.setGroup(true);
						events.add(p);
						dictDisplay.put(key, values);
					}
					event.setColor(isColor);
					isColor = !isColor;
					values.add(event);
					events.add(event);
				}
			}
		} else {
			for (EventModel event : data) {
				String value = event.getValueByIndex(index).trim();
				String key = value.substring(0, 1).toUpperCase();
				List<EventModel> values = dictDisplay.get(key);
				if (values == null) {
					values = new ArrayList<EventModel>();
					final EventModel p = new EventModel();
					p.setEventName(key);
					// System.out.println("KEY: " + key);
					p.setGroup(true);
					events.add(p);
					dictDisplay.put(key, values);
				}
				event.setColor(isColor);
				isColor = !isColor;
				values.add(event);
				events.add(event);
			}
		}
		mAdapter = new EventAdapter(mContext, R.layout.item_event, events,
				listener);
		mListView.setAdapter(mAdapter);
		Set<String> key1 = dictDisplay.keySet();
		Set<String> key = new TreeSet<String>(key1);
		char[] l = new char[key.size()];
		Iterator<String> iter = key.iterator();
		int i = 0;
		while (iter.hasNext()) {
			l[i] = iter.next().charAt(0);
			// System.out.println("i: " + i + " - " + l[i]);
			i++;
		}
		if (l.length > 0) {
			mSideBar.setVisibility(View.VISIBLE);
			mSideBar.setListView(mListView, a003_layout_listview, l);
		} else {
			mSideBar.setVisibility(View.GONE);
		}
	}

	private OnClickListListener listener = new OnClickListListener() {

		@Override
		public void onClick(EventModel data) {
			// TODO Auto-generated method stub
			((EventAdapter) mListView.getAdapter()).notifyDataSetChanged();
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// call any new activity here or do any thing you want here

				}
			}, 100);

			Intent i = new Intent(mContext, A004ListPeople.class);
			i.putExtra("mId", data.getEventId());
			i.putExtra("mTitle", data.getEventName());
			startActivityForResult(i, A004_LOGOUT);
			overridePendingTransition(0, android.R.anim.slide_out_right);
		}
	};

	@Override
	public void didClearText() {
		// TODO Auto-generated method stub
		updateListView(mEventListSource.getmListEvent(), null);
	}
}
